package socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Server3 {
    private ServerSocket serverSocket;
    //每链接一个客户端，把该客户端对应的输出流存入集合，用于广播发送消息给每一个客户端
    private List<PrintWriter> allOut = new ArrayList<>();

    public Server3(){
        try {
            System.out.println("正在启动服务器....");
            serverSocket = new ServerSocket(8091);
            System.out.println("服务器启动完毕!");
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    public void start(){

        try {
            while (true){
                System.out.println("等待客户端连接...");
                Socket socket = serverSocket.accept();
                System.out.println("一个客户端已经连接!");
                Runnable runnable = new ClientHandler(socket);
                Thread t = new Thread(runnable);
                t.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private class ClientHandler implements Runnable{
        private Socket socket;
        private String host;

        public ClientHandler(Socket socket){
            this.socket = socket;
            host = socket.getInetAddress().getHostAddress(); //获取socket的ip地址
        }
        public void run(){
            PrintWriter pw = null;
            try{
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(
                                socket.getInputStream()
                        )
                );
                //定义一组输出流，用来给客户端广播发送消息
                 pw = new PrintWriter(
                        new BufferedWriter(
                                new OutputStreamWriter(
                                        socket.getOutputStream()
                                )
                        ),true
                );
                synchronized(allOut){
                    allOut.add(pw);
                }
                System.out.println(host+"上线了，当前在线人数:"+allOut.size());
                sendMessage(host+"上线了，当前在线人数:"+allOut.size());

                String message ;
                while ((message = br.readLine()) != null){
                    System.out.println(host+"说："+message);
                    sendMessage(host+"说: "+message);
                }
            }catch (IOException e){
                e.printStackTrace();
            }finally {
                /*
                    当一个客户端发送完消息，断开链接后，把对应的输出流移除集合，避免再次写消息给该客户端
                 */
                synchronized (allOut) {
                    Iterator<PrintWriter> it = allOut.iterator();
                    while (it.hasNext()){
                        PrintWriter pw1 = it.next();
                        if (pw1 == pw){
                            it.remove();
                        }
                    }
                }
            }
        }
    }

    private void sendMessage(String message){
        synchronized (allOut) {
            for (PrintWriter pw : allOut){
                pw.println(message);
            }
        }
    }

    public static void main(String[] args) {
        Server3 server3 = new Server3();
        server3.start();
    }
}
